<template>
    <view class="bg-content">
        <div style="background-color: white; padding: 15px;">
            <u-form ref="validateFormRef" :model="validateForm.value" :label-width="200">
                <u-form-item label="店铺图片" prop="sysFileId" required>
                    <u-upload ref="uUpload" :multiple="false" :auto-upload="false" :max-count="1" :show-progress="false" :file-list="fileList"
                              @on-remove="onRemove($event)" @on-choose-complete="onChooseComplete($event)"></u-upload>
                </u-form-item>
                <u-form-item label="营业状态" prop="operatingStatus" required>
                    <u-input type="select" :select-open="validateForm.controls.operatingStatus.isShow" v-model="validateForm.controls.operatingStatus.textDesc"
                             placeholder="请选择营业状态" @click="validateForm.controls.operatingStatus.isShow = true; $forceUpdate();"></u-input>
                </u-form-item>
                <u-form-item label="系统分类" prop="storeClassId">
                    <u-input type="select" :select-open="validateForm.controls.storeClassId.isShow" v-model="validateForm.controls.storeClassId.textDesc"
                             placeholder="请选择系统分类" @click="validateForm.controls.storeClassId.isShow = true; $forceUpdate();"></u-input>
                </u-form-item>
                <u-form-item label="店铺名称" prop="name" required>
                    <u-input v-model="validateForm.value.name" placeholder="请输入店铺名称"/>
                </u-form-item>
                <u-form-item label="标题" prop="title" required>
                    <u-input v-model="validateForm.value.title" placeholder="请输入标题"/>
                </u-form-item>
                <u-form-item label="副标题" prop="subTitle">
                    <u-input v-model="validateForm.value.subTitle" placeholder="请输入副标题"/>
                </u-form-item>
                <u-form-item label="简介" prop="introduction">
                    <u-input type="textarea" height="40" v-model="validateForm.value.introduction" placeholder="请输入简介"/>
                </u-form-item>
                <u-form-item label="店铺地址" prop="address" required>
                    <u-input v-model="validateForm.value.address" placeholder="请输入店铺地址"/>
                </u-form-item>
                <u-form-item label="店铺坐标" prop="coordinate">
                    <u-input v-model="validateForm.value.coordinate" placeholder="请输入店铺坐标"/>
                    <u-button slot="right" type="success" size="mini" @click="navigateTo(`/pages/common/address-convert-coord-baidumap/index`)">获取</u-button>
                </u-form-item>
                <u-form-item label="工作日" prop="businessDays">
                    <u-input v-model="validateForm.value.businessDays" placeholder="请输入工作日，例如：周一至周日"/>
                </u-form-item>
                <u-form-item label="营业时间段" prop="businessHours">
                    <u-input v-model="validateForm.value.businessHours" placeholder="请输入营业时间段，例如：09:00-23:59或者08:30-12:00,14:00-22:00"/>
                </u-form-item>
                <u-form-item label="店铺标签" prop="storeLabel">
                    <u-input v-model="validateForm.value.storeLabel" placeholder="请输入店铺标签，例如：素食 甜品 顺德菜 快餐简餐 粤菜馆 咖啡厅 茶饮果汁 小吃 茶餐厅 海鲜 湘菜 粤式茶点 潮汕菜 火锅 自助餐 汤锅"/>
                </u-form-item>
                <u-form-item label="设施服务" prop="featureLabel">
                    <u-input v-model="validateForm.value.featureLabel" placeholder="请输入设施服务，例如：可停车，有WIFI，有包厢，有大桌, 充电宝，婴儿座"/>
                </u-form-item>
                <u-form-item label="联系电话" prop="phone" required>
                    <u-input v-model="validateForm.value.phone" placeholder="请输入联系电话"/>
                </u-form-item>
                <u-form-item label="邮箱" prop="email" required>
                    <u-input v-model="validateForm.value.email" placeholder="请输入邮箱"/>
                </u-form-item>
                <u-form-item label="验证码" prop="identifyingCode" required>
                    <u-input placeholder="请输入验证码" v-model="validateForm.value.identifyingCode" type="text"></u-input>
                    <u-button slot="right" type="success" size="mini" @click="getCode">{{codeTips}}</u-button>
                </u-form-item>
                <u-form-item label="支付宝账号" prop="alipayAccount" required>
                    <u-input v-model="validateForm.value.alipayAccount" placeholder="请输入支付宝账号"/>
                </u-form-item>
                <u-form-item label="支付宝真实姓名" prop="alipayRealName" required>
                    <u-input v-model="validateForm.value.alipayRealName" placeholder="请输入支付宝真实姓名"/>
                </u-form-item>
                <u-form-item label="每笔最小订单金额" prop="minOrderMoney" required>
                    <u-input v-model="validateForm.value.minOrderMoney" placeholder="请输入每笔最小订单金额"/>
                </u-form-item>
                <u-form-item label="销售模式" prop="saleMode" required>
                    <u-input type="select" :select-open="validateForm.controls.saleMode.isShow" v-model="validateForm.controls.saleMode.textDesc"
                             placeholder="请选择销售模式" @click="validateForm.controls.saleMode.isShow = true; $forceUpdate();"></u-input>
                </u-form-item>
                <u-form-item label="是否开启线上退款功能" prop="isSupportRefund" required>
                    <u-input type="select" :select-open="validateForm.controls.isSupportRefund.isShow" v-model="validateForm.controls.isSupportRefund.textDesc"
                             placeholder="请选择是否开启线上退款功能" @click="validateForm.controls.isSupportRefund.isShow = true; $forceUpdate();"></u-input>
                </u-form-item>
                <u-form-item label="买家确认收货是否交易完成" prop="isConfirmReceiptFinishOrder" required>
                    <u-input type="select" :select-open="validateForm.controls.isConfirmReceiptFinishOrder.isShow"
                             v-model="validateForm.controls.isConfirmReceiptFinishOrder.textDesc"
                             placeholder="请选择买家确认收货订单是否交易完成"
                             @click="validateForm.controls.isConfirmReceiptFinishOrder.isShow = true; $forceUpdate();"></u-input>
                </u-form-item>
                <u-form-item label="订单运费类型" prop="isConfirmReceiptFinishOrder" required>
                    <u-input type="select" :select-open="validateForm.controls.freightType.isShow" v-model="validateForm.controls.freightType.textDesc"
                             placeholder="请选择订单运费类型" @click="validateForm.controls.freightType.isShow = true; $forceUpdate();"></u-input>
                </u-form-item>
                <u-form-item label="订单运费金额" prop="freightMoney" required>
                    <u-input v-model="validateForm.value.freightMoney" placeholder="请输入订单运费金额"/>
                </u-form-item>
                <u-form-item label="订单免邮金额" prop="freeFreightMinOrderMoney" required v-if="validateForm.value.freightType == 1">
                    <u-input v-model="validateForm.value.freeFreightMinOrderMoney" placeholder="请输入订单免邮金额"/>
                </u-form-item>
            </u-form>

            <u-button type="error" @click="submit">提交</u-button>
        </div>

        <div class="table table-bordered" style="margin-top: 10px; background: white;">
            <div class="tr">
                <div class="td">
                    线上退款功能说明
                </div>
                <div class="td">
                    开启线上退款功能需要在移动端[我的]/[卖家中心]/[店铺保证金]中充值店铺保证金，销售中的商品才会对用户显示。<br/>
                    用户退款申请成功后支付宝将扣除订单支付金额的0.6%作为技术服务费（非平台收取）将由商家承担。
                </div>
            </div>
            <div class="tr">
                <div class="td">
                    支付宝设置说明
                </div>
                <div class="td">
                    请核实填写支付宝相关信息，资金回款时将使用该账户。
                </div>
            </div>
            <div class="tr">
                <div class="td">
                    销售模式说明
                </div>
                <div class="td">
                    普通模式（物流配送）：订单商品通过物流送达用户手里。凭券消费模式：用户凭订单生成的消费券号到店消费。
                </div>
            </div>
            <div class="tr">
                <div class="td">
                    买家确认收货订单是否交易完成说明
                </div>
                <div class="td">
                    如果是，则买家确认收货后，该订单视为交易完成，将不能再申请退款服务但可以申请售后相关服务。<br/>
                    由于订单交易完成，订单金额将立即回款商家设置的支付宝账户中。注意：该设置可能会影响用户购物体验，请谨慎考虑。
                </div>
            </div>
        </div>

        <!--邮箱验证码-->
        <u-verification-code seconds="60" ref="uCode" @change="codeChange"></u-verification-code>

        <u-select mode="mutil-column-auto" label-name="name" value-name="code" :mask-close-able="false" v-if="validateForm.controls.storeClassId.isShow"
                  v-model="validateForm.controls.storeClassId.isShow" :list="validateForm.controls.storeClassId.options"
                  :default-value="validateForm.controls.storeClassId.defaultValue"
                  @cancel="validateForm.controls.storeClassId.isShow = false; $forceUpdate();"
                  @confirm="UFormUtil.selectMutilColumnConfirm($event, validateForm.controls.storeClassId)"></u-select>

        <u-select mode="single-column" label-name="name" value-name="code" :mask-close-able="false"
                  v-model="validateForm.controls.operatingStatus.isShow" :list="validateForm.controls.operatingStatus.options"
                  :default-value="validateForm.controls.operatingStatus.defaultValue"
                  @cancel="validateForm.controls.operatingStatus.isShow = false; $forceUpdate();"
                  @confirm="UFormUtil.selectSingleColumnConfirm($event, validateForm.controls.operatingStatus)"></u-select>

        <u-select mode="single-column" label-name="name" value-name="code" :mask-close-able="false"
                  v-model="validateForm.controls.saleMode.isShow" :list="validateForm.controls.saleMode.options"
                  :default-value="validateForm.controls.saleMode.defaultValue"
                  @cancel="validateForm.controls.saleMode.isShow = false; $forceUpdate();"
                  @confirm="UFormUtil.selectSingleColumnConfirm($event, validateForm.controls.saleMode)"></u-select>

        <u-select mode="single-column" label-name="name" value-name="code" :mask-close-able="false"
                  v-model="validateForm.controls.isSupportRefund.isShow" :list="validateForm.controls.isSupportRefund.options"
                  :default-value="validateForm.controls.isSupportRefund.defaultValue"
                  @cancel="validateForm.controls.isSupportRefund.isShow = false; $forceUpdate();"
                  @confirm="UFormUtil.selectSingleColumnConfirm($event, validateForm.controls.isSupportRefund)"></u-select>

        <u-select mode="single-column" label-name="name" value-name="code" :mask-close-able="false"
                  v-model="validateForm.controls.isConfirmReceiptFinishOrder.isShow" :list="validateForm.controls.isConfirmReceiptFinishOrder.options"
                  :default-value="validateForm.controls.isConfirmReceiptFinishOrder.defaultValue"
                  @cancel="validateForm.controls.isConfirmReceiptFinishOrder.isShow = false; $forceUpdate();"
                  @confirm="UFormUtil.selectSingleColumnConfirm($event, validateForm.controls.isConfirmReceiptFinishOrder)"></u-select>

        <u-select mode="single-column" label-name="name" value-name="code" :mask-close-able="false"
                  v-model="validateForm.controls.freightType.isShow" :list="validateForm.controls.freightType.options"
                  :default-value="validateForm.controls.freightType.defaultValue"
                  @cancel="validateForm.controls.freightType.isShow = false; $forceUpdate();"
                  @confirm="UFormUtil.selectSingleColumnConfirm($event, validateForm.controls.freightType)"></u-select>
    </view>
</template>

<script>

    import {CommonService} from "@/dev/services/common.service";
    import {UFormUtil} from "@/dev/core/utils/u-form.util";
    import {CommonUtil} from "@/dev/core/utils/common.util";
    import {TbStoreService} from "@/dev/services/tb-store.service";
    import {LocalStorageUtil} from "@/dev/core/utils/local-storage.util";
    import {QiniuCloudUtil} from "@/dev/core/utils/qiniu-cloud.util";
    import {SysFileService} from "@/dev/services/sys-file.service";
    import {SysDictionaryService} from "@/dev/services/sys-dictionary.service";
    import {TbEmailIdentifyingCodeService} from "@/dev/services/tb_email_identifying_code.service";
    import {TbStoreClassService} from "@/dev/services/tb-store-class.service";

    export default {
        data() {
            return {
                codeTips: '',  // 获取验证码提示语
                fileList: [],
                validateForm: {
                    value: {
                        id: null,
                        sysFileId: '',  // 图片sysFile.id
                        communityId: '',
                        operatingStatus: false,
                        storeClassId: null,
                        name: '',
                        title: '',
                        subTitle: '',
                        introduction: '',
                        address: '',
                        coordinate: '',
                        businessDays: '',
                        businessHours: '',
                        storeLabel: '',
                        featureLabel: '',
                        minOrderMoney: '123',
                        phone: '',
                        email: '',
                        identifyingCode: '',
                        alipayAccount: '',
                        alipayRealName: '',
                        saleMode: null,
                        isSupportRefund: true,
                        isConfirmReceiptFinishOrder: false,
                        freightType: '0',
                        freightMoney: '0',
                        freeFreightMinOrderMoney: ''
                    },
                    rules: {
                        sysFileId: [
                            {required: true, message: '必填项!', trigger: ['change', 'blur']},
                            {pattern: /^(?=.*\S).+$/, message: '必填项!', trigger: ['change', 'blur']}
                        ],
                        name: [
                            {required: true, message: '必填项!', trigger: ['change', 'blur']},
                            {pattern: /^(?=.*\S).+$/, message: '必填项!', trigger: ['change', 'blur']},
                            {
                                trigger: ['blur'],
                                asyncValidator: (rule, value, callback) => {
                                    new CommonService().uniqueCheckByFields({
                                        "tableName": "tb_store",
                                        "fieldList": [
                                            {"fieldName": "community_id", "fieldValue": this.validateForm.value.communityId},
                                            {"fieldName": "name", "fieldValue": value}
                                        ],
                                        "excludeId": this.validateForm.value.id
                                    }).then(result => {
                                        if (result.status === "fail") {
                                            callback(new Error('输入的内容已存在！'));
                                        } else {
                                            callback()
                                        }
                                    });
                                }
                            }
                        ],
                        title: [
                            {required: true, message: '必填项!', trigger: ['change', 'blur']},
                            {pattern: /^(?=.*\S).+$/, message: '必填项!', trigger: ['change', 'blur']}
                        ],
                        address: [
                            {required: true, message: '必填项!', trigger: ['change', 'blur']},
                            {pattern: /^(?=.*\S).+$/, message: '必填项!', trigger: ['change', 'blur']}
                        ],
                        phone: [
                            {required: true, message: '必填项!', trigger: ['change', 'blur']},
                            {pattern: /^1[0-9]{10}$/, message: '请输入有效的手机号码!', trigger: ['change', 'blur']}
                        ],
                        email: [
                            {required: true, type: "email", message: '请输入有效的邮箱号码', trigger: ['change', 'blur']},
                        ],
                        identifyingCode: [
                            {required: true, message: '请输入邮箱验证码', trigger: ['change', 'blur']},
                            {
                                trigger: ['blur'],
                                asyncValidator: (rule, value, callback) => {
                                    new TbEmailIdentifyingCodeService().mailIdentifyingCodeCheck(this.validateForm.value.email, this.validateForm.value.identifyingCode).then(result => {
                                        if (result.status === "success") {
                                            callback()
                                        } else {
                                            callback(new Error('输入的邮箱验证码有误！'));
                                        }
                                    });
                                }
                            }
                        ],
                        minOrderMoney: [
                            {required: true, message: '必填项!', trigger: ['change', 'blur']},
                            {pattern: /^[0-9]+(.[0-9]{1,2})?$/, message: '请输入有效的金额!', trigger: ['change', 'blur']}
                        ],
                        alipayAccount: [
                            {required: true, message: '必填项!', trigger: ['change', 'blur']},
                            {pattern: /^(?=.*\S).+$/, message: '必填项!', trigger: ['change', 'blur']}
                        ],
                        alipayRealName: [
                            {required: true, message: '必填项!', trigger: ['change', 'blur']},
                            {pattern: /^(?=.*\S).+$/, message: '必填项!', trigger: ['change', 'blur']}
                        ],
                        saleMode: [
                            {required: true, message: '必填项!', trigger: ['change', 'blur']},
                            {pattern: /^(?=.*\S).+$/, message: '必填项!', trigger: ['change', 'blur']}
                        ],
                        freightType: [
                            {required: true, message: '必填项!', trigger: ['change', 'blur']},
                            {pattern: /^(?=.*\S).+$/, message: '必填项!', trigger: ['change', 'blur']}
                        ],
                        freightMoney: [
                            {required: true, message: '必填项!', trigger: ['change', 'blur']},
                            {pattern: /^[0-9]+(.[0-9]{1,2})?$/, message: '请输入大于或等于0且最多两位小数的金额!', trigger: ['change', 'blur']}
                        ],
                        freeFreightMinOrderMoney: [
                            {pattern: /^[0-9]+(.[0-9]{1,2})?$/, message: '必填项!', trigger: ['change', 'blur']},
                            {
                                trigger: ['blur'],
                                asyncValidator: (rule, value, callback) => {
                                    if (this.validateForm.value.freightType === "1") {
                                        if (value === "") {
                                            callback(new Error('请输入大于或等于0且最多两位小数的金额！'));
                                        } else {
                                            callback()
                                        }
                                    } else {
                                        callback()

                                    }
                                }
                            }
                        ],
                    }
                }
            }
        },
        onReady() {
            const _self = this;
            UFormUtil.setDefaultValues(this.validateForm, this.globalVariable.userInfo.tbStore);
            new SysFileService().findQiniuCloudImageUrl({
                fkId: _self.globalVariable.userInfo.tbStore.id,
                type: 'image/jpeg',
                typeMark: "store-brand"
            }).then(result => {
                if (result.url) {
                    _self.validateForm.value.sysFileId = result.id;
                    _self.fileList.push({
                        id: result.id,
                        url: result.url + "?_timestamp=" + new Date().getTime(),
                    });
                }
                _self.$forceUpdate()
            });

            new SysDictionaryService().optionList('tb_store@operating_status', null).then(result => {
                UFormUtil.setOptions(_self.validateForm.controls.operatingStatus, result);
                _self.$forceUpdate();
            });

            new TbStoreClassService().findTbStoreClassTree({
                communityId: _self.globalVariable.userInfo.tbStore.communityId,
                type: "1",
                status: "1",
                deleted: false
            }).then(result => {
                UFormUtil.setOptions(_self.validateForm.controls.storeClassId, [...CommonUtil.objectAlias(result[0].children, {'id': 'code'})], 2);
                _self.$forceUpdate();
            });

            new SysDictionaryService().optionList('tb_store@sale_mode', null).then(result => {
                UFormUtil.setOptions(_self.validateForm.controls.saleMode, result);
                _self.$forceUpdate();
            });

            UFormUtil.setOptions(_self.validateForm.controls.isSupportRefund, [{name: '否', code: "0"}, {name: '是', code: "1"}]);
            UFormUtil.setOptions(_self.validateForm.controls.isConfirmReceiptFinishOrder, [{name: '否', code: "0"}, {name: '是', code: "1"}]);

            new SysDictionaryService().optionList('tb_store@freight_type', null).then(result => {
                UFormUtil.setOptions(_self.validateForm.controls.freightType, result);
                _self.$forceUpdate();
            });

            _self.$forceUpdate();
        },
        methods: {
            codeChange(text) {
                this.codeTips = text;
            },
            // 获取验证码
            getCode() {
                const _self = this;
                if (this.$refs.uCode.canGetCode) {
                    // 模拟向后端请求验证码
                    uni.showLoading({
                        title: '正在获取验证码',
                        mask: true
                    });

                    new TbEmailIdentifyingCodeService().sendMailIdentifyingCode(this.validateForm.value.email).then(result => {
                        CommonUtil.alert(result.message);
                        uni.hideLoading();
                        // 通知验证码组件内部开始倒计时
                        _self.$refs.uCode.start();
                    });
                } else {
                    this.$u.toast('倒计时结束后再发送');
                }
            },
            onRemove($event) {
                console.log($event);
                const _self = this;
                new SysFileService().deleteSysFile({
                    id: _self.validateForm.value.sysFileId
                }).then(result => {
                    _self.validateForm.value.sysFileId = '';
                    UFormUtil.validation(_self.$refs.validateFormRef, 'sysFileId');
                    CommonUtil.toast("图片删除成功");
                    _self.$forceUpdate()
                });
            },
            onChooseComplete($event) {
                console.log($event);
                const _self = this;
                QiniuCloudUtil.uploadToCloud(_self.validateForm.value.id, $event[0].file.path, {typeMark: "store-brand"}).then(result => {
                    if (result.status === "success") {
                        _self.validateForm.value.sysFileId = result.id;
                        CommonUtil.toast(result.message);
                    } else {
                        CommonUtil.alert(result.message);
                    }
                    UFormUtil.validation(_self.$refs.validateFormRef, 'sysFileId');
                });
            },
            submit() {
                const _self = this;
                this.$refs.validateFormRef.validate(valid => {
                    if (valid) {
                        console.log('验证通过', _self.validateForm.value);

                        let data = _self.validateForm.value;
                        if (data.businessHours.indexOf(" ") !== -1) {
                            CommonUtil.toast('营业时间段不能出现空格，多个时间段用英文逗号隔开，例如：09:00-23:59或者08:30-12:00,14:00-22:00');
                            return;
                        }

                        CommonUtil.alert({
                            title: '提示！',
                            content: '确认提交吗？',
                            showCancel: true, // 是否显示取消按钮
                            success: function (res) {
                                if (res.cancel) { // 点击取消,默认隐藏弹框
                                } else { // 点击确定
                                    new TbStoreService().updateTbStore(_self.validateForm.value).then(result => {
                                        delete _self.validateForm.value.identifyingCode;
                                        Object.assign(_self.globalVariable.userInfo.tbStore, CommonUtil.deleteNullAttrInObject(result));
                                        LocalStorageUtil.setItem("userInfo", _self.globalVariable.userInfo);
                                        CommonUtil.toastNavigateBack('更新成功')
                                    });
                                }
                            }
                        });
                    } else {
                        console.log('验证失败');
                    }
                });
            }
        }
    }
</script>

<style lang="scss" scoped>
</style>
